const express = require("express");
const router = express.Router();
const {
  ACCESS_TOKEN_EXPIRES_IN,
  REFRESH_TOKEN_EXPIRES_IN,
} = require("../config/config");
const User = require("../models/user");
const { logger } = require("../server/logger");

const {
  generateAccessToken,
  generateRefreshToken,
  verifyToken,
} = require("./../utils/jwt");
const { getWechatSession, getUserInfo } = require("./../models/login");

// 购物车路由
router.get("/auth", (req, res) => {
  res.send("Hello Auth!");
});
// 后端登录接口
router.post("/auth/login", async (req, res) => {
  try {
    // 安全解构，提供默认值
    const { code = null, userInfo = {} } = req.body || {};
    console.log("code:", code);
    // 验证必要参数
    if (!code) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: "缺少必要的 code 参数",
      });
    }
    // 1. 用code换取openid (伪代码)
    const { openid } = await getWechatSession(code); // 调用微信接口获取openid
    console.log(openid);
    // 2. 查找或创建用户
    let user = await User.findOrCreateByOpenid(
      { openid },
      {
        nickName: "微信用户",
        avatarUrl:
          "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
        gender: "",
        city: "",
        province: "",
        country: "",
      }
    );
    // 3. 生成双token
    const access_token = generateAccessToken(user.id);
    const refresh_token = generateRefreshToken(user.id);
    console.log("access_token", access_token);
    console.log("refresh_token", refresh_token);
    logger.info(
      "这是一个测试日志 access_token" + JSON.stringify(access_token),
      {}
    );
    logger.info(
      "这是一个测试日志 refresh_token" + JSON.stringify(refresh_token),
      {}
    );
    return res.status(200).json({
      code: 0,
      success: true,
      data: {
        code: 200,
        access_token,
        refresh_token,
        access_expires_in: ACCESS_TOKEN_EXPIRES_IN,
        refresh_expires_in: REFRESH_TOKEN_EXPIRES_IN,
        userInfo: {
          id: user.id,
          nickName: user.nickName,
          avatarUrl: user.avatarUrl,
        },
      },
      message: "登录成功",
    });
  } catch (error) {
    console.error("登录失败:", error);
    return res.status(500).json({
      code: 500,
      message: "登录失败",
      error: error.message,
    });
  }
});

/**
 * @api {post} /auth/refresh 刷新Access Token
 * @apiName RefreshToken
 * @apiGroup Auth
 *
 * @apiParam {String} refresh_token 有效的refresh token
 *
 * @apiSuccess {String} access_token 新的access token
 * @apiSuccess {String} [refresh_token] 新的refresh token(可选)
 * @apiSuccess {Object} userInfo 用户基本信息
 */
router.post("/auth/refresh", async (req, res) => {
  console.log("原始refresh_token:", req.body.refresh_token); // 检查是否完整
  try {
    const { refresh_token } = req.body;
    console.log("刷新token", refresh_token);
    // 1. 验证refresh token是否提供
    if (!refresh_token) {
      return res.status(401).json({
        code: 401,
        message: "请提供refresh_token",
      });
    }

    // 2. 验证refresh token有效性
    let decoded;
    try {
      decoded = verifyToken(refresh_token);
    } catch (err) {
      console.log("err", err);
      // 区分不同类型的JWT错误
      if (err.name === "TokenExpiredError") {
        return res.status(401).json({
          code: 401,
          message: "refresh_token已过期，请重新登录",
        });
      }
      return res.status(401).json({
        code: 401,
        message: "无效的refresh_token",
      });
    }
    console.log("用户id:", decoded);
    // 3. 检查用户是否存在
    const user = await User.findById(decoded.userId);
    console.log("用户信息:", user);
    if (!user) {
      return res.status(401).json({
        code: 401,
        message: "用户不存在",
      });
    }

    // 4. 检查refresh token是否在有效期内
    // (可选)可以在这里添加额外的验证逻辑，比如检查token是否在黑名单中

    // 5. 生成新的access token
    const access_token = generateAccessToken(user.id);

    // 7. 返回响应
    res.status(200).json({
      code: 200,
      message: "token刷新成功",
        access_token:access_token,
        expires_in: ACCESS_TOKEN_EXPIRES_IN,
        userInfo: {
          userId: user.id,
          username: user.username,
          avatar: user.avatar,
        }
    });
  } catch (error) {
    console.error("刷新token失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
    });
  }
});

router.post("/token/verify", async (req, res) => {
  console.log("待验证token:", req.body.token); // 检查是否完整
  try {
    const { token } = req.body;
    // 1. 验证refresh token是否提供
    if (!token) {
      return res.status(401).json({
        code: 401,
        message: "请提供token",
      });
    }

    // 2. 验证refresh token有效性
    let decoded;
    try {
      decoded = verifyToken(token);
    } catch (err) {
      console.log("err", err);
      // 区分不同类型的JWT错误
      if (err.name === "TokenExpiredError") {
        return res.status(401).json({
          code: 401,
          message: "token已过期，请重新获取",
        });
      }
      return res.status(401).json({
        code: 401,
        message: "无效的token",
      });
    }

    // 4. 检查refresh token是否在有效期内

    // (可选)可以在这里添加额外的验证逻辑，比如检查token是否在黑名单中

    // 7. 返回响应
    res.status(200).json({
      code: 0,
      success: true,
      message: "token验证成功",
      data: { token: token },
    });
  } catch (error) {
    console.error("验证token失败:", error);
    res.status(500).json({
      code: 500,
      success: false,
      message: "服务器内部错误",
    });
  }
});

// 辅助函数：决定是否刷新refresh token
function shouldRefreshRefreshToken() {
  // 这里可以实现自定义逻辑，比如：
  // - 每次刷新都生成新的refresh token
  // - 只在refresh token快过期时刷新
  // - 基于安全策略决定
  return true; // 示例：总是刷新
}

module.exports = router;
